<template>
  <div class="feedback-container">
    <el-card>
      <div class="header-title">评价与反馈</div>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索岗位名称"
            style="width: 300px"
            clearable
            @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 岗位列表 -->
      <el-table :data="positions" border stripe style="width: 100%; margin-top: 20px;">
        <el-table-column prop="name" label="岗位名称" align="center" />
        <el-table-column prop="teacherName" label="发布教师" align="center" />
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="viewFeedbacks(scope.row)"
            >
              查看评价
            </el-button>
            <el-button
                v-if="scope.row.hasWorked"
                type="success"
                size="small"
                @click="showRatingDialog(scope.row)"
            >
              评价
            </el-button>
            <el-button
                v-else
                type="info"
                size="small"
                disabled
            >
              未工作过
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
            background
            layout="prev, pager, next, jumper, ->, total"
            :total="total"
            :page-size="pageSize"
            :current-page="pageNum"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 查看评价对话框 -->
    <el-dialog
        v-model="viewDialogVisible"
        title="岗位评价"
        width="600px"
        :before-close="handleViewDialogClose"
    >
      <div class="feedback-list">
        <div v-if="currentFeedbacks.length === 0" class="no-feedback">
          暂无评价
        </div>
        <div v-else class="feedback-items">
          <div
              v-for="feedback in currentFeedbacks"
              :key="feedback.id"
              class="feedback-item"
              :class="{ 'own-feedback': feedback.isOwn }"
          >
            <div class="feedback-header">
              <span class="student-name" :class="{ 'own-name': feedback.isOwn }">
                {{ feedback.studentName }}
                <el-tag v-if="feedback.isOwn" type="success" size="small">我的评价</el-tag>
              </span>
              <div class="rating">
                <el-rate
                    v-model="feedback.rating"
                    disabled
                    show-score
                    text-color="#ff9900"
                />
              </div>
            </div>
            <div class="feedback-comment">{{ feedback.comment }}</div>
            <div class="feedback-time">{{ formatTime(feedback.createTime) }}</div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 评价对话框 -->
    <el-dialog
        v-model="ratingDialogVisible"
        title="提交评价"
        width="500px"
        :before-close="handleRatingDialogClose"
    >
      <el-form :model="ratingForm" :rules="ratingRules" ref="ratingFormRef" label-width="80px">
        <el-form-item label="评分" prop="rating">
          <el-rate
              v-model="ratingForm.rating"
              show-score
              text-color="#ff9900"
              score-template="{value}分"
          />
        </el-form-item>
        <el-form-item label="评价内容" prop="comment">
          <el-input
              v-model="ratingForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入您的评价内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ratingDialogVisible = false">返回</el-button>
          <el-button type="primary" @click="submitRating" :loading="submitting">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import axios from 'axios';

const positions = ref([]);
const searchKeyword = ref('');
const viewDialogVisible = ref(false);
const ratingDialogVisible = ref(false);
const currentFeedbacks = ref([]);
const currentPosition = ref(null);
const submitting = ref(false);
const ratingFormRef = ref(null);

// 分页相关
const pageNum = ref(1);
const pageSize = ref(8);
const total = ref(0);

const ratingForm = reactive({
  positionId: null,
  rating: 0,
  comment: ''
});

const ratingRules = {
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' }
  ],
  comment: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 5, message: '评价内容至少5个字符', trigger: 'blur' }
  ]
};

// 获取岗位列表
const fetchPositions = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.error('请先登录');
      return;
    }
    const res = await axios.get('/api/feedback/positions', {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        positionName: searchKeyword.value || undefined
      },
      headers: { Authorization: `Bearer ${token}` }
    });
    if (res.data.code === 0) {
      positions.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      ElMessage.error(res.data.msg || '获取岗位列表失败');
    }
  } catch (e) {
    ElMessage.error('请求失败: ' + e.message);
  }
};

// 查看评价
const viewFeedbacks = async (position) => {
  try {
    const token = localStorage.getItem('token');
    const res = await axios.get(`/api/feedback/position/${position.id}`, {
      headers: { Authorization: `Bearer ${token}` }
    });
    if (res.data.code === 0) {
      currentFeedbacks.value = res.data.data;
      currentPosition.value = position;
      viewDialogVisible.value = true;
    } else {
      ElMessage.error(res.data.msg || '获取评价失败');
    }
  } catch (e) {
    ElMessage.error('请求失败: ' + e.message);
  }
};

// 显示评价对话框
const showRatingDialog = (position) => {
  currentPosition.value = position;
  ratingForm.positionId = position.id;
  ratingForm.rating = 0;
  ratingForm.comment = '';
  ratingDialogVisible.value = true;
};

// 提交评价
const submitRating = async () => {
  if (!ratingFormRef.value) return;

  try {
    await ratingFormRef.value.validate();
  } catch (e) {
    return;
  }

  submitting.value = true;
  try {
    const token = localStorage.getItem('token');
    const res = await axios.post('/api/feedback/submit', ratingForm, {
      headers: { Authorization: `Bearer ${token}` }
    });
    if (res.data.code === 0) {
      ElMessage.success('评价提交成功');
      ratingDialogVisible.value = false;
      // 刷新岗位列表
      fetchPositions();
    } else {
      ElMessage.error(res.data.msg || '评价提交失败');
    }
  } catch (e) {
    ElMessage.error('请求失败: ' + e.message);
  } finally {
    submitting.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pageNum.value = 1; // 重置到第一页
  fetchPositions();
};

// 分页处理
const handlePageChange = (val) => {
  pageNum.value = val;
  fetchPositions();
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleString();
};

// 对话框关闭处理
const handleViewDialogClose = () => {
  viewDialogVisible.value = false;
  currentFeedbacks.value = [];
  currentPosition.value = null;
};

const handleRatingDialogClose = () => {
  ratingDialogVisible.value = false;
  currentPosition.value = null;
  ratingForm.positionId = null;
  ratingForm.rating = 0;
  ratingForm.comment = '';
};

onMounted(() => {
  fetchPositions();
});
</script>

<style scoped>
.feedback-container {
  padding: 24px;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #222;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.feedback-list {
  max-height: 400px;
  overflow-y: auto;
}

.no-feedback {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.feedback-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.feedback-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 16px;
  background-color: #fafafa;
}

.feedback-item.own-feedback {
  border-color: #67c23a;
  background-color: #f0f9ff;
}

.feedback-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.student-name {
  font-weight: bold;
  color: #333;
}

.student-name.own-name {
  color: #67c23a;
}

.feedback-comment {
  color: #666;
  line-height: 1.5;
  margin-bottom: 8px;
}

.feedback-time {
  color: #999;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}
</style>